#include<Windows.h>
#include"Controller.h"

int8_t ControllerRead(CONTROLLER* controller, uint16_t addr);
void ControllerWrite(CONTROLLER* controller, uint16_t addr, int8_t dat);
void SetKeyState(CONTROLLER* controller, DWORD wParam, bool state);

void ControllerInit(CONTROLLER*controller)
{
	controller->read = ControllerRead;
	controller->write = ControllerWrite;
	controller->SetKeyState = SetKeyState;
}
enum BUTTON_MASK
{
	BUTTONA = 0x40,
	BUTTOND = 0x80,
	BUTTONW = 0x10,
	BUTTONS = 0x20,
	BUTTONJ = 0x01,
	BUTTONK = 0x02,
	BUTTONU = 0x04,
	BUTTONI = 0x08
};
void SetKeyState(CONTROLLER *controller,DWORD wParam,bool keystate)
{
	enum BUTTON_MASK button=0;
	switch (wParam)
	{
	case 'A':
	case 'a':
		button = BUTTONA;
		break;
	case 'D':
	case 'd':
		button = BUTTOND;
		break;
	case 'W':
	case 'w':
		button = BUTTONW;
		break;
	case 'S':
	case 's':
		button = BUTTONS;
		break;
	case 'J':
	case 'j':
		button = BUTTONJ;
		break;
	case 'K':
	case 'k':
		button = BUTTONK;
		break;
	case 'U':
	case 'u':
		button = BUTTONU;
		break;
	case 'I':
	case 'i':
		button = BUTTONI;
		break;
	}
	if (keystate)
	{
		controller->state |= (int8_t)button;
	}
	else
	{
		controller->state &= ~((int8_t)button);
	}
}
int8_t ControllerRead(CONTROLLER *controller,uint16_t addr)
{
	if (addr == (uint16_t)(0x4016))
	{
		if (controller->ready)
		{
			return (int8_t)(controller->state >> (controller->mask++) & 1);
		}
		else if (addr == (uint16_t)(0x4017))
		{

		}
		return 0;
	}
	return 0;
}
void ControllerWrite(CONTROLLER* controller, uint16_t addr,int8_t dat)
{
	if (addr == (uint16_t)(0x4016))
	{
		if ((dat & 1) == 1)
		{
			controller->ready = false;
			controller->mask = 0;
		}
		else if ((dat & 1) == 0 && controller->ready == false)
		{
			controller->ready = true;
		}
		else if (addr == (uint16_t)(0x4017))
		{

		}
	}
}